import json
import datetime
import math
from urllib.parse import urlparse

from flask import Blueprint, request, jsonify, Response, current_app
from sqlalchemy import desc
from app.core.extensions import db
from app.models.user import User
from app.models.recognition_record import RecognitionRecord


# 创建蓝图
recognition_bp = Blueprint('recognition', __name__)


# 创建识别记录（内部API，只供系统内部调用）
@recognition_bp.route('/recognition/record', methods=['POST'])
def create_recognition_record():
    try:
        data = request.get_json()

        # 验证必填字段
        required_fields = ['user_id', 'recognition_type', 'recognition_result']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 1,
                    'message': f'缺少必填字段: {field}',
                    'data': {}
                }), 400

        # 获取用户信息
        user = User.query.get(data.get('user_id'))
        if not user:
            return jsonify({
                'code': 1,
                'message': '用户不存在',
                'data': {}
            }), 404

        # 处理设备信息，只保存手机型号
        raw_user_agent = data.get('device_info', request.headers.get('User-Agent', ''))
        device_model = get_mobile_model(raw_user_agent)

        # 记录完整的设备信息到日志
        current_app.logger.info(
            f"用户识别设备信息 - 用户ID:{data.get('user_id')} - 原始UA:{raw_user_agent} - 提取型号:{device_model}")

        # 创建识别记录
        record = RecognitionRecord(
            user_id=data.get('user_id'),
            username=user.nick_name,
            real_name=data.get('real_name'),
            recognition_type=data.get('recognition_type'),
            recognition_result=data.get('recognition_result'),
            success_rate=data.get('success_rate'),
            recognition_image=data.get('recognition_image'),
            device_info=device_model,  # 使用处理后的设备型号
            ip_address=request.remote_addr,
            location=data.get('location')
        )

        # 处理识别数据
        if 'recognition_data' in data:
            if isinstance(data['recognition_data'], dict):
                record.recognition_data = json.dumps(data['recognition_data'])
            elif isinstance(data['recognition_data'], str):
                record.recognition_data = data['recognition_data']

        db.session.add(record)
        db.session.commit()

        return jsonify({
            'code': 0,
            'message': '创建识别记录成功',
            'data': {'record_id': record.id}
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 1,
            'message': f'创建识别记录失败: {str(e)}',
            'data': {}
        }), 500


# 获取用户识别记录
@recognition_bp.route('/user/recognition/records', methods=['GET'])
def get_user_recognition_records():
    user_id = request.args.get('user_id')
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)

    if not user_id:
        return jsonify({
            'code': 1,
            'message': '缺少必填参数: user_id',
            'data': {}
        }), 400

    # 验证用户存在
    user = User.query.get(user_id)
    if not user:
        return jsonify({
            'code': 1,
            'message': '用户不存在',
            'data': {}
        }), 404

    # 查询该用户的识别记录
    query = RecognitionRecord.query.filter_by(user_id=user_id)

    # 按时间倒序排列
    query = query.order_by(RecognitionRecord.created_at.desc())

    # 获取总数
    total = query.count()

    # 计算总页数
    pages = math.ceil(total / limit) if total > 0 else 1

    # 分页
    offset = (page - 1) * limit
    records = query.offset(offset).limit(limit).all()

    # 准备响应数据
    result = []
    for record in records:
        # 处理识别数据（JSON字符串转为字典）
        recognition_data = {}
        if record.recognition_data:
            try:
                recognition_data = json.loads(record.recognition_data)
            except json.JSONDecodeError:
                pass

        result.append({
            'id': record.id,
            'recognition_type': record.recognition_type,
            'recognition_result': record.recognition_result,
            'success_rate': record.success_rate,
            'recognition_image': record.recognition_image,
            'recognition_data': recognition_data,
            'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S') if record.created_at else None
        })

    return jsonify({
        'code': 0,
        'message': '获取用户识别记录成功',
        'data': {
            'items': result,
            'total': total,
            'page': page,
            'pages': pages,
            'per_page': limit
        }
    })


# 查询用户单条识别记录详情
@recognition_bp.route('/user/recognition/records/<int:record_id>', methods=['GET'])
def get_user_recognition_detail(record_id):
    user_id = request.args.get('user_id')

    if not user_id:
        return jsonify({
            'code': 1,
            'message': '缺少必填参数: user_id',
            'data': {}
        }), 400

    # 查询识别记录并验证属于该用户
    record = RecognitionRecord.query.get(record_id)
    if not record:
        return jsonify({
            'code': 1,
            'message': '识别记录不存在',
            'data': {}
        }), 404

    if str(record.user_id) != str(user_id):
        return jsonify({
            'code': 1,
            'message': '无权访问该记录',
            'data': {}
        }), 403

    # 处理识别数据（JSON字符串转为字典）
    recognition_data = {}
    if record.recognition_data:
        try:
            recognition_data = json.loads(record.recognition_data)
        except json.JSONDecodeError:
            pass

    # 准备响应数据
    record_data = {
        'id': record.id,
        'recognition_type': record.recognition_type,
        'recognition_result': record.recognition_result,
        'success_rate': record.success_rate,
        'recognition_image': record.recognition_image,
        'recognition_data': recognition_data,
        'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S') if record.created_at else None
    }

    return jsonify({
        'code': 0,
        'message': '获取识别记录详情成功',
        'data': record_data
    })


# 添加手机型号识别函数
def get_mobile_model(user_agent):
    """从User-Agent中提取手机型号信息"""
    import re

    if not user_agent:
        return 'Unknown'

    user_agent = user_agent.lower()

    # 处理iPhone
    if 'iphone' in user_agent:
        # 尝试提取iPhone具体型号，例如 iPhone14,3
        iphone_match = re.search(r'iphone\s*(\d+[,_]\d+)', user_agent)
        if iphone_match:
            return f'iPhone {iphone_match.group(1)}'
        return 'iPhone'

    # 处理iPad
    if 'ipad' in user_agent:
        ipad_match = re.search(r'ipad\s*(\d+[,_]\d+)', user_agent)
        if ipad_match:
            return f'iPad {ipad_match.group(1)}'
        return 'iPad'

    # 处理Android设备
    if 'android' in user_agent:
        # 检查常见品牌和型号
        # 华为设备
        if 'huawei' in user_agent or 'honor' in user_agent:
            model_match = re.search(r'(huawei|honor)[- _]([a-z0-9-]+)', user_agent)
            if model_match:
                brand = 'Huawei' if model_match.group(1) == 'huawei' else 'Honor'
                return f"{brand} {model_match.group(2).upper()}"
            return 'Huawei/Honor'

        # 小米设备
        if 'xiaomi' in user_agent or 'redmi' in user_agent or ' mi ' in user_agent:
            model_match = re.search(r'(xiaomi|redmi|mi)[- _]([a-z0-9-]+)', user_agent)
            if model_match:
                brand = 'Xiaomi' if model_match.group(1) in ['xiaomi', 'mi'] else 'Redmi'
                return f"{brand} {model_match.group(2).upper()}"
            return 'Xiaomi'

        # OPPO设备
        if 'oppo' in user_agent:
            model_match = re.search(r'oppo[- _]([a-z0-9-]+)', user_agent)
            if model_match:
                return f"OPPO {model_match.group(1).upper()}"
            return 'OPPO'

        # vivo设备
        if 'vivo' in user_agent:
            model_match = re.search(r'vivo[- _]([a-z0-9-]+)', user_agent)
            if model_match:
                return f"vivo {model_match.group(1).upper()}"
            return 'vivo'

        # 三星设备
        if 'samsung' in user_agent:
            model_match = re.search(r'(sm-[a-z0-9]+)', user_agent)
            if model_match:
                return f"Samsung {model_match.group(1).upper()}"
            return 'Samsung'

        # OnePlus设备
        if 'oneplus' in user_agent:
            model_match = re.search(r'oneplus[- _]([a-z0-9-]+)', user_agent)
            if model_match:
                return f"OnePlus {model_match.group(1).upper()}"
            return 'OnePlus'

        # 其他Android设备，尝试从Build信息获取
        build_match = re.search(r'build/([a-z0-9_.]+)', user_agent)
        if build_match:
            return f"Android {build_match.group(1).upper()}"

        # 默认返回Android
        return 'Android'

    # 处理PC设备
    if 'windows' in user_agent:
        win_match = re.search(r'windows nt (\d+\.\d+)', user_agent)
        if win_match:
            win_versions = {
                '10.0': 'Windows 10/11',
                '6.3': 'Windows 8.1',
                '6.2': 'Windows 8',
                '6.1': 'Windows 7',
                '6.0': 'Windows Vista',
                '5.2': 'Windows XP x64',
                '5.1': 'Windows XP'
            }
            return win_versions.get(win_match.group(1), f"Windows {win_match.group(1)}")
        return 'Windows'

    if 'macintosh' in user_agent or 'mac os' in user_agent:
        mac_match = re.search(r'mac os x (\d+[._]\d+)', user_agent)
        if mac_match:
            return f"Mac OS {mac_match.group(1).replace('_', '.')}"
        return 'Mac OS'

    # 处理其他设备
    if 'linux' in user_agent:
        return 'Linux'

    # 未知设备
    return 'Unknown'


# 管理员获取所有识别记录列表
@recognition_bp.route('/admin/recognition/records', methods=['GET'])
def get_recognition_records():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    username = request.args.get('username', '')
    recognition_type = request.args.get('recognition_type', '')
    recognition_result = request.args.get('recognition_result', '')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')
    user_id = request.args.get('user_id', type=int)  # 添加用户ID参数
    code = request.args.get('code', '').strip()  # 添加激活码参数

    query = RecognitionRecord.query

    # 应用筛选条件
    if username:
        query = query.filter(
            RecognitionRecord.username.like(f'%{username}%') |
            RecognitionRecord.real_name.like(f'%{username}%')
        )

    # 通过用户ID筛选
    if user_id:
        query = query.filter(RecognitionRecord.user_id == user_id)

    # 通过激活码筛选（需要先查找激活码关联的用户ID）
    if code:
        try:
            # 从激活码表查找使用此激活码的用户ID
            from app.models import ActivationCode
            activation_code = ActivationCode.query.filter_by(code=code).first()
            if activation_code and activation_code.used_by:
                # 如果找到激活码并且已被使用，则通过用户ID筛选识别记录
                query = query.filter(RecognitionRecord.user_id == activation_code.used_by)
            else:
                # 如果未找到激活码或激活码未使用，则返回空结果但保留分页信息
                return jsonify({
                    'code': 0,
                    'message': '未找到该激活码对应的用户记录',
                    'data': {
                        'items': [],
                        'total': 0,
                        'page': page,
                        'pages': 0,
                        'per_page': limit
                    }
                })
        except Exception as e:
            current_app.logger.error(f"通过激活码查询失败: {str(e)}")

    if recognition_type:
        query = query.filter(RecognitionRecord.recognition_type == recognition_type)

    if recognition_result:
        query = query.filter(RecognitionRecord.recognition_result == recognition_result)

    if start_date and end_date:
        try:
            query = query.filter(
                RecognitionRecord.created_at.between(
                    datetime.datetime.strptime(start_date, '%Y-%m-%d'),
                    datetime.datetime.strptime(end_date + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
                )
            )
        except ValueError:
            pass  # 日期格式错误时忽略此条件
    # 获取总数
    total = query.count()
    query = query.order_by(desc(RecognitionRecord.id))  # 或者你也可以用 desc(RecognitionRecord.created_at)
    # 计算总页数
    pages = math.ceil(total / limit) if total > 0 else 1

    # 分页
    offset = (page - 1) * limit

    records = query.offset(offset).limit(limit).all()

    # 准备响应数据
    result = []
    for record in records:
        result.append({
            'id': record.id,
            'user_id': record.user_id,
            'username': record.username,
            'real_name': record.real_name,
            'recognition_type': record.recognition_type,
            'recognition_result': record.recognition_result,
            'photo_url': record.photo_url,
            'success_rate': record.success_rate,
            'device_info': record.device_info,
            'ip_address': record.ip_address,
            'location': record.location,
            'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S') if record.created_at else None
        })

    return jsonify({
        'code': 0,
        'message': '获取识别记录成功',
        'data': {
            'items': result,
            'total': total,
            'page': page,
            'pages': pages,
            'per_page': limit
        }
    })


# 统计分析API
@recognition_bp.route('/admin/recognition/statistics', methods=['GET'])
def get_recognition_statistics():
    recognition_type = request.args.get('recognition_type', '')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')
    time_dimension = request.args.get('time_dimension', 'day')  # 时间维度：day, week, month
    # 新增参数：按日期获取前十用户
    top_users_type = request.args.get('top_users_type', '')
    specific_date = request.args.get('date', '')

    # 如果是获取特定日期的前十用户，单独处理
    if top_users_type == 'daily' and specific_date:
        try:
            # 解析日期
            date_obj = datetime.datetime.strptime(specific_date, '%Y-%m-%d')
            next_day = date_obj + datetime.timedelta(days=1)

            # 查询该日期的记录
            daily_records = RecognitionRecord.query.filter(
                RecognitionRecord.created_at >= date_obj,
                RecognitionRecord.created_at < next_day
            ).all()

            # 按用户分组统计
            user_stats = {}
            for record in daily_records:
                user_id = record.user_id
                if user_id not in user_stats:
                    user_stats[user_id] = {
                        'user_id': user_id,
                        'username': record.username,
                        'count': 0,
                        'success': 0,
                        'failed': 0
                    }

                user_stats[user_id]['count'] += 1
                if record.recognition_result == 'success':
                    user_stats[user_id]['success'] += 1
                else:
                    user_stats[user_id]['failed'] += 1

            # 转换为列表并计算成功率
            daily_top_users = []
            for user_id, stats in user_stats.items():
                success_rate = round((stats['success'] / stats['count'] * 100), 1) if stats['count'] > 0 else 0
                daily_top_users.append({
                    'user_id': stats['user_id'],
                    'username': stats['username'],
                    'count': stats['count'],
                    'success_count': stats['success'],
                    'failed_count': stats['failed'],
                    'success_rate': success_rate
                })

            # 按识别次数排序，取前十名
            daily_top_users.sort(key=lambda x: x['count'], reverse=True)
            daily_top_users = daily_top_users[:10]

            return jsonify({
                'code': 0,
                'message': '获取每日用户统计数据成功',
                'data': {
                    'daily_top_users': daily_top_users
                }
            })

        except Exception as e:
            return jsonify({
                'code': 1,
                'message': f'获取每日用户统计数据失败: {str(e)}',
                'data': {}
            }), 500

    # 基础查询
    query = RecognitionRecord.query

    # 应用筛选条件
    if recognition_type:
        query = query.filter(RecognitionRecord.recognition_type == recognition_type)

    date_filter = None
    if start_date and end_date:
        try:
            date_filter = RecognitionRecord.created_at.between(
                datetime.datetime.strptime(start_date, '%Y-%m-%d'),
                datetime.datetime.strptime(end_date + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
            )
        except ValueError:
            pass  # 日期格式错误时忽略此条件
    elif start_date:
        try:
            date_filter = RecognitionRecord.created_at >= datetime.datetime.strptime(start_date, '%Y-%m-%d')
        except ValueError:
            pass
    elif end_date:
        try:
            date_filter = RecognitionRecord.created_at <= datetime.datetime.strptime(end_date + ' 23:59:59',
                                                                                     '%Y-%m-%d %H:%M:%S')
        except ValueError:
            pass

    if date_filter:
        query = query.filter(date_filter)

    # 获取所有记录，减少重复查询，提高性能
    all_records = query.all()

    # 计算总体统计数据
    total_count = len(all_records)
    success_count = sum(1 for record in all_records if record.recognition_result == 'success')
    failed_count = total_count - success_count
    success_rate = round((success_count / total_count * 100), 1) if total_count > 0 else 0

    # 获取日期范围
    if start_date and end_date:
        try:
            start = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            end = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        except ValueError:
            # 默认显示最近7天/4周/12个月 (根据时间维度)
            end = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
            if time_dimension == 'day':
                start = end - datetime.timedelta(days=6)  # 7天
            elif time_dimension == 'week':
                start = end - datetime.timedelta(weeks=4)  # 4周
            else:  # month
                start = end.replace(month=end.month - 12 if end.month > 12 else end.month + 12 - 12,
                                    year=end.year - 1 if end.month <= 12 else end.year)  # 12个月
    else:
        # 默认显示最近7天/4周/12个月 (根据时间维度)
        end = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        if time_dimension == 'day':
            start = end - datetime.timedelta(days=6)  # 7天
        elif time_dimension == 'week':
            start = end - datetime.timedelta(weeks=4)  # 4周
        else:  # month
            start = end.replace(month=end.month - 12 if end.month > 12 else end.month + 12 - 12,
                                year=end.year - 1 if end.month <= 12 else end.year)  # 12个月

    # 时间维度数据
    time_series = []

    # 函数：获取记录归属的时间标识
    def get_time_identifier(record_datetime, dimension):
        if dimension == 'day':
            return record_datetime.strftime('%Y-%m-%d')
        elif dimension == 'week':
            # 获取周标识：年份-周数
            year, week, _ = record_datetime.isocalendar()
            return f"{year}-W{week:02d}"
        else:  # month
            return record_datetime.strftime('%Y-%m')

    # 生成所有时间点
    time_points = []
    current = start
    if time_dimension == 'day':
        while current <= end:
            time_points.append((current.strftime('%Y-%m-%d'), current, current + datetime.timedelta(days=1)))
            current += datetime.timedelta(days=1)
    elif time_dimension == 'week':
        # 调整到周一开始
        current = current - datetime.timedelta(days=current.weekday())
        while current <= end:
            year, week, _ = current.isocalendar()
            time_id = f"{year}-W{week:02d}"
            next_week = current + datetime.timedelta(days=7)
            time_points.append((time_id, current, next_week))
            current = next_week
    else:  # month
        # 调整到月初
        current = current.replace(day=1)
        while current <= end:
            time_id = current.strftime('%Y-%m')
            if current.month == 12:
                next_month = current.replace(year=current.year + 1, month=1)
            else:
                next_month = current.replace(month=current.month + 1)
            time_points.append((time_id, current, next_month))
            current = next_month

    # 按时间维度分组统计
    time_stats = {}
    for record in all_records:
        time_id = get_time_identifier(record.created_at, time_dimension)
        if time_id not in time_stats:
            time_stats[time_id] = {'count': 0, 'success': 0, 'failed': 0}

        time_stats[time_id]['count'] += 1
        if record.recognition_result == 'success':
            time_stats[time_id]['success'] += 1
        else:
            time_stats[time_id]['failed'] += 1

    # 整理时间序列数据
    for time_id, start_time, end_time in time_points:
        stats = time_stats.get(time_id, {'count': 0, 'success': 0, 'failed': 0})
        success_rate_value = round((stats['success'] / stats['count'] * 100), 1) if stats['count'] > 0 else 0

        time_display = time_id
        if time_dimension == 'day':
            time_display = start_time.strftime('%m-%d')  # 简化显示，仅显示月-日
        elif time_dimension == 'week':
            time_display = f"第{time_id.split('W')[1]}周"  # 简化显示，仅显示周数

        time_series.append({
            'time_id': time_id,
            'time_display': time_display,
            'count': stats['count'],
            'success_count': stats['success'],
            'failed_count': stats['failed'],
            'success_rate': success_rate_value
        })

    # 用户统计 - 获取识别次数最多的前10名用户
    user_stats = {}
    for record in all_records:
        user_id = record.user_id
        if user_id not in user_stats:
            user_stats[user_id] = {
                'user_id': user_id,
                'username': record.username,
                'count': 0,
                'success': 0,
                'failed': 0
            }

        user_stats[user_id]['count'] += 1
        if record.recognition_result == 'success':
            user_stats[user_id]['success'] += 1
        else:
            user_stats[user_id]['failed'] += 1

    # 转换为列表并计算成功率
    top_users = []
    for user_id, stats in user_stats.items():
        success_rate_value = round((stats['success'] / stats['count'] * 100), 1) if stats['count'] > 0 else 0
        top_users.append({
            'user_id': stats['user_id'],
            'username': stats['username'],
            'count': stats['count'],
            'success_count': stats['success'],
            'failed_count': stats['failed'],
            'success_rate': success_rate_value
        })

    # 按识别次数排序，取前10名
    top_users.sort(key=lambda x: x['count'], reverse=True)
    top_users = top_users[:10]

    # 计算类型分布
    type_distribution = []
    types = ['face', 'id_card', 'drive_license']
    type_counts = {'face': 0, 'id_card': 0, 'drive_license': 0}

    for record in all_records:
        if record.recognition_type in type_counts:
            type_counts[record.recognition_type] += 1

    for rtype in types:
        type_count = type_counts.get(rtype, 0)
        type_percentage = round((type_count / total_count * 100), 1) if total_count > 0 else 0

        type_display = rtype
        if rtype == 'face':
            type_display = '人脸识别'
        elif rtype == 'id_card':
            type_display = '身份证'
        elif rtype == 'drive_license':
            type_display = '驾驶证'

        type_distribution.append({
            'type': rtype,
            'type_display': type_display,
            'count': type_count,
            'percentage': type_percentage
        })

    # 计算设备分布
    device_stats = {}
    for record in all_records:
        if not record.device_info:
            continue

        # 从User-Agent中提取手机型号
        device_type = get_mobile_model(record.device_info)

        if device_type not in device_stats:
            device_stats[device_type] = 0
        device_stats[device_type] += 1

    device_distribution = []
    for device, count in device_stats.items():
        percentage = round((count / total_count * 100), 1) if total_count > 0 else 0
        device_distribution.append({
            'device': device,
            'count': count,
            'percentage': percentage
        })

    # 按设备数量排序，使主要设备显示在前面
    device_distribution.sort(key=lambda x: x['count'], reverse=True)

    # 限制返回前10种设备类型，其余归为"其他"
    if len(device_distribution) > 10:
        # 计算其余设备总数
        others_count = sum(item['count'] for item in device_distribution[10:])
        others_percentage = round((others_count / total_count * 100), 1) if total_count > 0 else 0

        # 保留前10种设备，并添加"其他"类别
        device_distribution = device_distribution[:10]
        if others_count > 0:
            device_distribution.append({
                'device': '其他设备',
                'count': others_count,
                'percentage': others_percentage
            })

    # 组装响应数据
    data = {
        'total_count': total_count,
        'success_count': success_count,
        'failed_count': failed_count,
        'success_rate': success_rate,
        'time_dimension': time_dimension,
        'time_series': time_series,
        'type_distribution': type_distribution,
        'device_distribution': device_distribution,
        'top_users': top_users
    }

    return jsonify({
        'code': 0,
        'message': '获取识别统计数据成功',
        'data': data
    })


# 导出识别记录统计报告
@recognition_bp.route('/admin/recognition/export', methods=['GET'])
def export_recognition_statistics():
    from io import StringIO
    import csv
    from flask import Response

    recognition_type = request.args.get('recognition_type', '')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')
    export_type = request.args.get('export_type', 'basic')  # basic, detailed, user_stats

    # 基础查询
    query = RecognitionRecord.query

    # 应用筛选条件
    if recognition_type:
        query = query.filter(RecognitionRecord.recognition_type == recognition_type)

    if start_date and end_date:
        try:
            query = query.filter(
                RecognitionRecord.created_at.between(
                    datetime.datetime.strptime(start_date, '%Y-%m-%d'),
                    datetime.datetime.strptime(end_date + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
                )
            )
        except ValueError:
            pass

    # 按时间倒序排列
    query = query.order_by(RecognitionRecord.created_at.desc())

    # 获取所有记录
    records = query.all()

    # 创建CSV文件
    csv_data = StringIO()
    csv_writer = csv.writer(csv_data)

    # 根据导出类型生成不同的报表
    if export_type == 'detailed':
        # 详细记录报表
        csv_writer.writerow([
            'ID', '用户ID', '用户名', '识别类型', '识别结果',
            '识别率', '设备信息', 'IP地址', '地理位置', '创建时间'
        ])

        for record in records:
            csv_writer.writerow([
                record.id,
                record.user_id,
                record.username,
                record.recognition_type,
                record.recognition_result,
                record.success_rate,
                record.device_info,
                record.ip_address,
                record.location,
                record.created_at.strftime('%Y-%m-%d %H:%M:%S') if record.created_at else ''
            ])

    elif export_type == 'user_stats':
        # 用户统计报表
        user_stats = {}

        for record in records:
            user_id = record.user_id
            if user_id not in user_stats:
                user_stats[user_id] = {
                    'user_id': user_id,
                    'username': record.username,
                    'count': 0,
                    'success': 0,
                    'failed': 0
                }

            user_stats[user_id]['count'] += 1
            if record.recognition_result == 'success':
                user_stats[user_id]['success'] += 1
            else:
                user_stats[user_id]['failed'] += 1

        # 写入CSV表头
        csv_writer.writerow([
            '用户ID', '用户名', '识别总次数', '成功次数', '失败次数', '成功率'
        ])

        # 按照识别次数排序
        sorted_users = sorted(user_stats.values(), key=lambda x: x['count'], reverse=True)

        for user in sorted_users:
            success_rate = round((user['success'] / user['count'] * 100), 1) if user['count'] > 0 else 0
            csv_writer.writerow([
                user['user_id'],
                user['username'],
                user['count'],
                user['success'],
                user['failed'],
                f"{success_rate}%"
            ])

    else:  # basic - 按日期统计的基础报表
        # 按日期分组统计
        date_stats = {}

        for record in records:
            date_str = record.created_at.strftime('%Y-%m-%d')
            if date_str not in date_stats:
                date_stats[date_str] = {
                    'date': date_str,
                    'count': 0,
                    'success': 0,
                    'failed': 0
                }

            date_stats[date_str]['count'] += 1
            if record.recognition_result == 'success':
                date_stats[date_str]['success'] += 1
            else:
                date_stats[date_str]['failed'] += 1

        # 写入CSV表头
        csv_writer.writerow([
            '日期', '识别总次数', '成功次数', '失败次数', '成功率'
        ])

        # 按日期排序
        sorted_dates = sorted(date_stats.values(), key=lambda x: x['date'])

        for date_item in sorted_dates:
            success_rate = round((date_item['success'] / date_item['count'] * 100), 1) if date_item['count'] > 0 else 0
            csv_writer.writerow([
                date_item['date'],
                date_item['count'],
                date_item['success'],
                date_item['failed'],
                f"{success_rate}%"
            ])

    # 生成文件名
    report_type_name = {
        'basic': '基础统计',
        'detailed': '详细记录',
        'user_stats': '用户统计'
    }.get(export_type, '统计报告')

    date_range = ''
    if start_date and end_date:
        date_range = f"{start_date}至{end_date}"
    elif start_date:
        date_range = f"{start_date}以后"
    elif end_date:
        date_range = f"截至{end_date}"
    else:
        date_range = datetime.datetime.now().strftime('%Y-%m-%d')

    filename = f"识别记录{report_type_name}_{date_range}.csv"

    # 返回CSV文件
    response = Response(
        csv_data.getvalue().encode('utf-8-sig'),  # 使用BOM标记，解决Excel中文乱码问题
        mimetype='text/csv',
        headers={
            'Content-Disposition': f'attachment; filename="{filename}"'
        }
    )

    return response


# 删除单个识别记录
@recognition_bp.route('/admin/recognition/records/<int:record_id>', methods=['DELETE'])
def delete_recognition_record(record_id):
    try:
        record = RecognitionRecord.query.get(record_id)
        if not record:
            return jsonify({
                'code': 1,
                'message': '识别记录不存在',
                'data': {}
            }), 404
        delImage = delete_file_from_cos(record.recognition_image)  # 删除COS存储的图片文件
        if not delImage:
            return jsonify({
                'code': 1,
                'message': '腾讯云失败联系技术支持',
                'data': {}
            }), 404
        db.session.delete(record)
        db.session.commit()

        return jsonify({
            'code': 0,
            'message': '删除识别记录成功',
            'data': {}
        })

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除识别记录失败: {str(e)}")
        return jsonify({
            'code': 1,
            'message': f'删除识别记录失败: {str(e)}',
            'data': {}
        }), 500


# 批量删除识别记录
@recognition_bp.route('/admin/recognition/records/batch', methods=['DELETE'])
def batch_delete_recognition_records():
    try:
        data = request.get_json()
        ids = data.get('ids', [])

        if not ids:
            return jsonify({
                'code': 1,
                'message': '未提供要删除的记录ID',
                'data': {}
            }), 400

        # 查找所有要删除的记录
        records = RecognitionRecord.query.filter(RecognitionRecord.id.in_(ids)).all()

        # 删除记录
        for record in records:
            delImage = delete_file_from_cos(record.recognition_image)  # 删除COS存储的图片文件
            if delImage:
                db.session.delete(record)

        db.session.commit()

        return jsonify({
            'code': 0,
            'message': f'成功删除 {len(records)} 条识别记录',
            'data': {}
        })

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"批量删除识别记录失败: {str(e)}")
        return jsonify({
            'code': 1,
            'message': f'批量删除识别记录失败: {str(e)}',
            'data': {}
        }), 500


# 管理员获取单条识别记录详情
@recognition_bp.route('/admin/recognition/records/<int:record_id>', methods=['GET'])
def admin_get_recognition_detail(record_id):
    try:
        # 查询识别记录
        record = RecognitionRecord.query.get(record_id)
        if not record:
            return jsonify({
                'code': 1,
                'message': '识别记录不存在',
                'data': {}
            }), 404

        # 处理识别数据（JSON字符串转为字典）
        recognition_data = {}
        if record.recognition_data:
            try:
                recognition_data = json.loads(record.recognition_data)
            except json.JSONDecodeError:
                pass

        # 准备响应数据
        record_data = {
            'id': record.id,
            'user_id': record.user_id,
            'username': record.username,
            'real_name': record.real_name,
            'recognition_type': record.recognition_type,
            'recognition_result': record.recognition_result,
            'success_rate': record.success_rate,
            'recognition_image': record.recognition_image,
            'photo_url': record.photo_url,
            'recognition_data': recognition_data,
            'device_info': record.device_info,
            'ip_address': record.ip_address,
            'location': record.location,
            'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S') if record.created_at else None
        }

        return jsonify({
            'code': 0,
            'message': '获取识别记录详情成功',
            'data': record_data
        })

    except Exception as e:
        current_app.logger.error(f"获取识别记录详情失败: {str(e)}")
        return jsonify({
            'code': 1,
            'message': f'获取识别记录详情失败: {str(e)}',
            'data': {}
        }), 500

def extract_cos_key(file_url):
    """
    从腾讯云 COS URL 中提取文件 key
    """
    parsed_url = urlparse(file_url)
    return parsed_url.path.lstrip('/').strip()  # 去掉开头的 /


def delete_file_from_cos(filename):
    """
    删除 COS 上指定的文件
    :param filename: 文件在 COS 上的 Key（如 xxx.png）
    :return: 删除结果 dict
    """
    from qcloud_cos import CosConfig, CosS3Client
    import logging

    # 腾讯云 COS 配置
    secret_id = 'AKIDCUZS8arwqY9WhgT2OZWFnYMCqIix0uc7'
    secret_key = 'KRTJwMadV9c0HLFaprfHhutfEakgR1NW'
    region = 'ap-guangzhou'
    bucket = 'xfjf-1310081316'
    token = None
    scheme = 'https'

    # 初始化客户端
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
    cos_client = CosS3Client(config)

    try:
        cos_client.delete_object(
            Bucket=bucket,
            Key=extract_cos_key(filename)  # 提取文件 key
        )
        return True
    except Exception as e:
        logging.error(f"删除文件失败: {e}")
        return False
